<template>
    <div class="app-center">
        <header-bar>
            <a-breadcrumb class="app-breadcrumb">
                <a-breadcrumb-item>
                    <router-link :to="`/setting/permission`">
                        权限管理
                    </router-link>
                </a-breadcrumb-item>
                <a-breadcrumb-item>权限列表</a-breadcrumb-item>
            </a-breadcrumb>
        </header-bar>
        <div class="app-inner clearfix">
            <table-toolbar>
                <div>
                    <a-button type="primary" @click="showAdd(null)" size="large">添加权限
                    </a-button>
                </div>
                <div class="search" slot="search">


                    <a-input placeholder="搜索" v-model="keyWord" style="width: auto;margin-left: 16px;"
                             @pressEnter="onSearchEnter">
                        <a-icon type="search" slot="prefix"></a-icon>
                    </a-input>
                </div>
            </table-toolbar>
            <a-table :pagination="false" :rowKey="record => record.name" :dataSource="table.data"
                     :columns="table.columns"
                     :locale="table.locale" :loading="table.loading"
                     @change="handleTableChange">
                <template slot="is_menu" slot-scope="is_menu, record">
                    <a-badge status="success" v-if="is_menu == 1" text="是"></a-badge>
                    <a-badge status="error" v-else text="否"></a-badge>
                </template>
                <template slot="action" slot-scope="id, record">
                    <h-link @click="showAdd(record)">添加</h-link>
                    <a-divider type="vertical"/>
                    <a-dropdown>
                        <a class="ant-dropdown-link">操作
                            <a-icon type="down"/>
                        </a>
                        <a-menu slot="overlay">
                            <a-menu-item>
                                查看
                            </a-menu-item>
                            <a-menu-item @click="showAdd(record,true)">
                                编辑
                            </a-menu-item>
                            <a-menu-item :disabled="record.created_name == 'system'" @click="showDelete(record)">
                                删除
                            </a-menu-item>
                        </a-menu>
                    </a-dropdown>
                </template>
            </a-table>
        </div>

        <a-drawer width=640 :title="modal.title" :visible="modal.showAdd" placement="right" :maskClosable="false"
                  :closable="false"
                  @close="onClosePermission">
            <a-form @submit="onSubmitPermission" :autoFormCreate="(form) => this.permissionForm = form"
                    class="staff-form">
                <a-row :gutter="16">
                    <a-col :span="12">
                        <a-form-item label="显示名称"
                                     fieldDecoratorId="display_name"
                                     :fieldDecoratorOptions="{rules: [{ required: true, message: '请填写显示名称'}],initialValue:modal.default.display_name}">
                            <a-input placeholder="请输入显示名称"></a-input>
                        </a-form-item>
                    </a-col>
                    <a-col :span="12">
                        <a-form-item label="简称"
                                     fieldDecoratorId="short_name"
                                     :fieldDecoratorOptions="{initialValue:modal.default.short_name}">
                            <a-input placeholder="请输入简称"></a-input>
                        </a-form-item>
                    </a-col>
                    <a-col :span="12">
                        <a-form-item label="权限"
                                     fieldDecoratorId="name"
                                     :fieldDecoratorOptions="{rules: [{ required: true, message: '请填写权限'}],initialValue:modal.default.name}">
                            <a-input placeholder="请输入权限"></a-input>
                        </a-form-item>
                    </a-col>
                    <a-col :span="12">
                        <a-form-item label="上级权限"
                                     fieldDecoratorId="pid"
                                     :fieldDecoratorOptions="{rules: [{ required: true, message: '请选择上级权限'}],initialValue:modal.default.pid}"
                        >
                            <a-select>
                                <a-select-option v-for="item in groups" :key="item.key" :name="item.value"><p>
                                    <span v-for="i in item.level - 1" :key="`space-${i}`" class="space"></span>{{item.display_name}}
                                </p></a-select-option>
                            </a-select>
                        </a-form-item>
                    </a-col>


                </a-row>
                <a-row :gutter="16">
                    <a-col :span="24">
                        <a-form-item label="是否为菜单" fieldDecoratorId="is_menu"
                                     :fieldDecoratorOptions="{initialValue:modal.default.is_menu}">
                            <a-radio-group name="is_menu" :defaultValue="1" @change="onIsMenuChange">
                                <a-radio :value="1">是</a-radio>
                                <a-radio :value="0">否</a-radio>
                            </a-radio-group>
                        </a-form-item>
                    </a-col>
                    <template v-if="modal.default.is_menu == 1">
                        <a-col :span="24">
                            <a-form-item label="图标类型" fieldDecoratorId="icon_type"
                                         :fieldDecoratorOptions="{initialValue:modal.default.icon_type}">
                                <a-radio-group @change="onChangeIconType">
                                    <a-radio-button value="none">无图标</a-radio-button>
                                    <a-radio-button value="system">系统图标</a-radio-button>
                                    <a-radio-button value="iconfont">Iconfont图标</a-radio-button>
                                    <a-radio-button value="custom">自定义图片图标</a-radio-button>
                                </a-radio-group>
                            </a-form-item>
                        </a-col>
                        <a-col :span="12">
                            <a-form-item label="菜单链接" fieldDecoratorId="url"
                                         :fieldDecoratorOptions="{initialValue:modal.default.url}">
                                <a-input placeholder="请输入链接"></a-input>
                            </a-form-item>
                        </a-col>
                        <a-col :span="12" v-if="modal.default.icon_type != 'none'">
                            <a-form-item label="图标" fieldDecoratorId="icon"
                                         :fieldDecoratorOptions="{initialValue:modal.default.icon}">
                                <a-input placeholder="请输入图标"></a-input>
                            </a-form-item>
                        </a-col>
                    </template>
                </a-row>
                <a-row :gutter="16">
                    <a-col :span="24">
                        <a-form-item label="简介" fieldDecoratorId="description"
                                     :fieldDecoratorOptions="{initialValue:modal.default.description}">
                            <a-textarea :rows="4" placeholder="请输入简介"/>
                        </a-form-item>
                    </a-col>
                </a-row>

                <div class="form-buttons">
                    <a-button style="margin-right: 8px;" @click="onClosePermission">
                        取消
                    </a-button>
                    <a-button type="primary" :loading="modal.confirmLoading" htmlType="submit">
                        {{modal.edit ? '保存':'提交'}}
                    </a-button>
                </div>
            </a-form>
        </a-drawer>


    </div>
</template>

<script lang="jsx">
    import HeaderBar from "../../../components/HeaderBar";
    import TableToolbar from "../../../components/table-toolbar";
    import {loadTreePermissions} from '@/api/setting/manager'
    import util from '@/libs/util'
    import {createPermission, updatePermission, deletePermission} from '@/api/setting/permission'


    import {mapState} from 'vuex'
    import HLink from "../../../components/HLink";


    export default {
        name: "permission",
        components: {HLink, TableToolbar, HeaderBar},
        data() {
            return {
                permissionForm: null,
                keyWord: "",
                role: undefined,
                currentMenu: ['permission'],
                visible: false,
                viewDrawer: {
                    visible: false,
                    item: {},

                },
                modal: {
                    showAdd: false,
                    confirmLoading: false,
                    title: "添加权限",
                    edit: false,
                    default: {
                        pid: "",
                        icon_type: "",
                        is_menu: 1,
                        display_name: "",
                        short_name: "",
                        description: "",
                        name: "",
                        icon: "",
                        url: ""
                    }
                },
                formItemLayout: {
                    labelCol: {span: 4},
                    wrapperCol: {span: 20},
                },
                groups: [],
                table: {
                    loading: false,
                    columns: [
                        {
                            title: "名称",
                            dataIndex: 'display_name',
                        },
                        {
                            title: "简称",
                            dataIndex: 'short_name',
                        },
                        {
                            title: "权限",
                            dataIndex: "name"
                        },
                        {
                            title: "图标",
                            dataIndex: "icon"
                        },
                        {
                            title: "菜单",
                            dataIndex: "is_menu",
                            scopedSlots: {customRender: 'is_menu'},
                        },
                        {
                            title: "链接",
                            dataIndex: "url",

                        },
                        {
                            title: '操作',
                            key: 'action',
                            scopedSlots: {customRender: 'action'},

                        }
                    ],
                    data: [],
                    locale: {
                        emptyText: "~没有更多数据了~"
                    },
                    noDataText: '~没有更多数据了~',

                },

            }
        },

        computed: {
            ...mapState("admin/user", [
                'info'
            ]),

        },


        mounted() {
            this.loadData();
            this.loadGroup();

        },

        methods: {
            onChangeIconType(e) {
                console.log(e);
                this.modal.default.icon_type = e.target.value
            },
            onIsMenuChange(e) {
                this.modal.default.is_menu = e.target.value;
                if (this.modal.default.is_menu == 1) {
                    this.modal.default_icon_type = 'none'
                }
            },
            showAdd(record, edit = false) {
                this.modal.edit = edit;
                this.modal.default = {};
                this.modal.default.icon_type = 'none';
                this.modal.default.is_menu = 1;
                if (record && record.id) {

                    if (edit) {
                        this.modal.title = '编辑权限'
                        this.modal.default = record
                        this.modal.default.pid = record.pid + ""

                    } else {
                        this.modal.default.pid = record.id + ""
                    }
                } else {
                    this.modal.default.pid = "0"

                    this.modal.title = '添加权限'
                }
                this.modal.showAdd = true
            },
            showDelete(record) {
                this.$confirm({
                    title: '提示',
                    content: '删除后不可恢复，确定删除吗？',

                    onOk: (e) => {
                        return new Promise((resolve, reject) => {
                            deletePermission(record.id).then(res => {
                                this.reloadData()
                                resolve(res)
                            }).catch(error => {
                                reject(error)
                            })
                        }).catch(() => console.log('Oops errors!'));
                    }
                });
            },
            showDrawer(item) {
                this.visible = true

            },
            onClosePermission() {
                this.modal.showAdd = false
                this.permissionForm.resetFields()
            },
            reloadData() {
                this.onClosePermission()
                this.loadData()
                this.loadGroup()
                this.$store.dispatch('admin/menu/load', true)
                this.$store.dispatch('admin/menu/mapMenu', this.$route)
            },
            onSubmitPermission(e) {
                e.preventDefault()
                this.permissionForm.validateFields((err, values) => {
                    console.log(values)
                    if (!err) {
                        this.modal.confirmLoading = true
                        if (this.modal.edit && this.modal.default.id) {
                            updatePermission(values, this.modal.default.id).then(res => {
                                this.modal.confirmLoading = false
                                this.reloadData();
                                this.$message.success('保存成功')
                            }).catch(error => {
                                this.modal.confirmLoading = false
                            })
                        } else {
                            createPermission(values).then(res => {
                                this.modal.confirmLoading = false
                                this.reloadData();
                                this.$message.success('添加成功')
                            }).catch(error => {
                                this.modal.confirmLoading = false
                            })
                        }
                    }
                })

            },
            handleAdd() {

            },
            onCloseDrawer() {
                this.visible = false
            },
            onSearchEnter() {
                this.loadData()
            },

            showPermission(record) {

            },

            loadGroup() {
                loadTreePermissions({group: 1}).then(res => {
                    // console.log(res)
                    let children = res;
                    let parent = {
                        id: 0,
                        key: '0',
                        value: "0",
                        pid: "",
                        label: '无上级权限',
                        children,
                        display_name: '无上级权限',
                        name: ""
                    };

                    this.groups = this.mapData([parent])

                }).catch(error => {
                    console.error(error);
                })
            },
            mapData(data) {
                let array = [];
                util.spread(data, array);
                console.log(array);
                array.map(item => {
                    item.pId = item.pid;
                    item.label = item.display_name;
                    item.key = item.id + '';
                    item.value = item.id;
                    return item;
                })
                return array;

                // let tree = data.map(item => {
                //     item.value = item.id + "";
                //     item.label = item.display_name;
                //     item.key = item.name;
                //     if (item.children && item.children.length > 0) {
                //         let children = this.mapData(item.children)
                //         item.children = children
                //     }
                //     return item
                // })
                // return tree
            },

            handleTableChange(pagination, filters, sorts) {
                const pager = {...this.pagination};
                pager.current = pagination.current;
                this.table.pagination = pager;
            },
            loadData() {
                this.table.loading = true
                let params = {};
                if (this.keyWord) {
                    params.keyword = this.keyWord
                }
                loadTreePermissions(params).then(res => {
                    console.log(res)
                    this.table.loading = false
                    this.table.data = res
                }).catch(error => {
                    this.table.loading = false
                    console.error(error);
                })
            }
        }
    }
</script>

<style scoped lang="less">
    .top-menu {
        height: 50px;
        line-height: 50px;
        border-bottom: 1px solid #e5e5e5;
    }

    .clearfix {
        zoom: 1;
    }

    a.disabled {
        color: #989898;
        cursor: not-allowed;
    }

    .app-center {
        .app-inner {
            margin: 10px;
            padding: 15px;
            min-width: 750px;
            min-height: 500px;
            box-shadow: 0 0 1px 0 rgba(0, 0, 0, .2);
            background-color: #fff;
            .app-pagination {
                margin-top: 16px;
                margin-left: auto;
                text-align: right;
            }
        }
    }

    .form-buttons {
        position: absolute;
        bottom: 0;
        width: 100%;
        border-top: 1px solid #e8e8e8;
        padding: 10px 16px;
        text-align: right;
        left: 0;
        background: #fff;
        border-radius: 0 0 4px 4px;
    }

    .space {
        width: 16px;
        display: inline-block;
    }


</style>
